package eu.irreality.dai.gameplay.actions.stairs;

import java.util.Iterator;

import eu.irreality.dai.gameplay.actions.Action;
import eu.irreality.dai.gameplay.entities.AliveEntity;
import eu.irreality.dai.gameplay.entities.PlayerCharacter;
import eu.irreality.dai.gameplay.entities.Stairs;
import eu.irreality.dai.gameplay.world.GameWorld;
import eu.irreality.dai.ui.cell.DisplayableObject;
import eu.irreality.dai.util.Position;
import eu.irreality.dai.util.SortedList;
import eu.irreality.dai.util.exceptions.GameException;
import eu.irreality.dai.util.exceptions.InternalErrorException;
import eu.irreality.dai.world.level.Level;

public abstract class UseStairsAction extends Action
{

    public abstract boolean isUp();

    public UseStairsAction(GameWorld world, AliveEntity entity)
    {
	super(world, entity);
    }

    public void execute() throws GameException, InternalErrorException
    {
	Level level = world.getActiveLevel(); // TODO Wrong.

	Position pos = entity.getPosition();

	SortedList stuff = level.get(pos);
	for (Iterator it = stuff.iterator(); it.hasNext();)
	{
	    DisplayableObject dobj = (DisplayableObject) it.next();
	    if (dobj instanceof Stairs)
	    {
		Stairs stairs = (Stairs) dobj;
		if (stairs.isUp() == this.isUp())
		{
		    Level l = stairs.getDestinationLevel();
		    Position p = stairs.getDestinationPosition();
		    // l.addEntity(entity);
		    // System.out.println("Dest pos " + p);
		    // l.add(entity,p.getRow(),p.getCol());
		    level.removeEntity(entity);
		    l.addEntity(entity, p.getRow(), p.getCol());
		    if (entity instanceof PlayerCharacter)
			world.setActiveLevel(l);
		    break;
		}
	    }
	}

    }

}
